<?php

/**
 * This is the model class for table "public.page_widget".
 */
require_once(dirname(__FILE__).'/base/PageWidgetBase.php');
class PageWidget extends PageWidgetBase
{
    //use in searchByWidget
    public $pageUrl;
    public $workflowId;
    
    public function behaviors()
    {
        return array(
            'timestamp'=>array(
                'class'=>'TimestampBehavior',
            ),
        );
    }
    
    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'page' => array(self::BELONGS_TO, 'Page', 'page_id'),
            'contentType' => array(self::BELONGS_TO, 'ContentType', 'content_type_id'),
            'widget' => array(self::BELONGS_TO, 'CmsWidget', 'widget_id'),
            'currentWorkflow' => array(self::BELONGS_TO, 'PageCurrentRevision', 'page_id'),
        );
    }
    
    public function getContext() {
        eval('$settings ='.$this->widget_settings.';');
        $context = ContentContext::model()->findByPk($settings['meta']['context_id']);
        
        return $context;
    }
    
    public function getWidgetSettings(){
        // prepare the widget setting if it's empty or not an array
        if (empty($this->widget_settings)) $this->widget_settings = "''";
        eval('$settings ='.$this->widget_settings.';');
        if (!is_array($settings)) 
            $settings = array(
                'meta'      => array(),
                'widget'    => array(),
                'data'      => array(),
                'layout'    => array()
            );
        else {
            if (!isset($settings['data']))
                $settings['data'] = array();
            if (!isset($settings['widget']))
                $settings['widget'] = array();
            if (!isset($settings['layout']))
                $settings['layout'] = array();
            if (!isset($settings['meta']))
                $settings['meta'] = array();
        }

        
        // convert constant 'page_widget.widget_data_id' into real widget_data_id
        if ($this->widget_data_id > 0 && 
            isset($settings['data']['params']) && 
            isset($settings['data']['params'][':id']) &&
            $settings['data']['params'][':id'] == 'page_widget.widget_data_id')
            $settings['data']['params'][':id'] = $this->widget_data_id;
        
        return $settings;        
    }
    
    /**
    * 
    * @return BaseCmsWidget a widget class which is derived from BaseCmsWidget
    */
    /*public function getWidgetComponent(){
        // try to create widget
        $widget = $this->widget;
        if (!$widget) {
            FErrorHandler::logError('Widget not found for ID '.$this->content_type_id);
            return '';
        }
        
        return $widget->createWidgetForPage($this);
    }*/
    
    public function renderHtml()
    {
        $widget = $this->widget;
        if (!is_object($widget)) {
            FErrorHandler::logError('Widget not found for ID '.$this->content_type_id);
            return 'page_widget_id '.$this->id;
        }
        
        $route = $widget->path;
        
        ob_start();
        ob_implicit_flush(false);
        ContentBaseController::$forceRenderPartial = true;
        ContentBaseController::$pageWidget = $this;
        try {
            /*if (is_string($this->widget_settings))
                $this->widget_settings = $this->evaluateExpression($this->widget_settings);
            $get = array();
            if (is_array($this->widget_settings) && count($this->widget_settings))
            {
                $get = array_keys($this->widget_settings);
                foreach ($this->widget_settings as $key => $val)
                    $_GET[$key] = $val;
            }*/
            Yii::app()->runController($route);
            /*if (count($get))
            {
                foreach ($get as $key)
                    unset($_GET[$key]);
            }*/
        }
        catch (CHttpException $e)
        {
            Yii::log(CVarDumper::dumpAsString($e->getMessage()), CLogger::LEVEL_ERROR);
            Yii::log(CVarDumper::dumpAsString($e->getTraceAsString()), CLogger::LEVEL_ERROR);
            if (YII_DEBUG)
                echo $e->getMessage();
        }
        ContentBaseController::$pageWidget = null;
        ContentBaseController::$forceRenderPartial = false;
        if (ContentBaseController::$pageTitle !== null)
            Yii::app()->controller->pageTitle = ContentBaseController::$pageTitle;
        $html = ob_get_clean();
        return $html;
    }
    /*public function renderHtml() {
        $contentType = $this->contentType;

        // todo: fix this ! It's possible that a widget is not related to a content type, i.e. Google Analytics
        if (!$contentType){
            FErrorHandler::logError('Content type not found for ID '.$this->content_type_id);
            return '';
        }
        try{
            $com = $this->getWidgetComponent();
            $html = $com->run();
        }catch (CException $e)
        {
            Yii::log($e->getMessage(), CLogger::LEVEL_ERROR);
            if (YII_DEBUG)
                $html = $e->getMessage();
            else
                $html = '';
        }
        return $html;
    }*/
    
    public function searchByWidget($siteId, $widgetId=0)
    {
        $criteria=new CDbCriteria;
        $criteria->with = array(
            'page'=>array(
                'select'=>array('title', 'site_id'),
                'with'=>array(
                    'defaultUrl'=>array(
                        'select'=>'url',
                    ),
                )
            ),
            'widgetLayout'=>array(
                'select'=>array('name'),
            ),
            'widgetData'=>array(
                'joinType'=>'INNER JOIN',
                'select'=>false,
                'with'=>array(
                    'widget'=>array(
                        'joinType'=>'INNER JOIN',
                        'select'=>false,
                        'on'=>'"widget".id='.(int) $widgetId,
                    )
                )
            ),
        );
        $criteria->join = 'LEFT JOIN page_current_revision pcr ON "pcr".page_id = "t".page_id AND "pcr".revision = "t".revision_id';
        
        $criteria->select = array('container', 'ordering', 'status', 'page_id', 'revision_id', 'widget_layout_id');
        $criteria->distinct = true;
        
        $criteria->compare('"page".site_id',$siteId);
        if ($this->workflowId)
            $criteria->compare('"pcr".workflow_id', $this->workflowId);
        $criteria->addSearchCondition('"t".container',$this->container, true, 'AND', 'LIKE');
        $criteria->addSearchCondition('"page".title',$this->page_id, true, 'AND', 'LIKE');
        $criteria->addSearchCondition('"widgetLayout".name',$this->widget_layout_id, true, 'AND', 'LIKE');
        $criteria->addSearchCondition('"defaultUrl".url',$this->pageUrl, true, 'AND', 'LIKE');
        
        return new CActiveDataProvider(get_class($this), array(
            'criteria'=>$criteria,
            'sort'=>array(
                'defaultOrder'=>'"page".title ASC, "t".container ASC, "t".revision_id ASC, "t".ordering ASC',
                'attributes'=>array(
                    'page_id'=>array(
                        'asc'=>'"page".title ASC',
                        'desc'=>'"page".title DESC',
                    ),
                    'pageUrl'=>array(
                        'asc'=>'"defaultUrl".url ASC',
                        'desc'=>'"defaultUrl".url DESC',
                    ),
                    'widget_layout_id'=>array(
                        'asc'=>'"widgetLayout".name ASC',
                        'desc'=>'"widgetLayout".name DESC',
                    ),
                    'container',
                )
            ),
            'pagination'=>array(
                'pageSize'=>Settings::BO_PAGE_SIZE,
            ),
        ));
    }
}
